from database import database

def get_fault_counts():
    """获取故障数量统计"""
    conn = database.get_db_connection()
    cursor = conn.cursor()
    # 只获取前端需要的字段
    cursor.execute("""
        SELECT id, phase, hardware_resource_pool, software_manufacturer, 
               fault_handling_count, created_at 
        FROM fault_counts
    """)
    counts = cursor.fetchall()
    conn.close()
    
    return [dict(count) for count in counts]

def get_manufacturer_stats():
    """获取厂家故障统计"""
    conn = database.get_db_connection()
    cursor = conn.cursor()
    # 只获取前端需要的字段
    cursor.execute("""
        SELECT id, manufacturer, device_type, optical_module, cpu_non_domestic, 
               cpu_domestic_hygon, cpu_domestic_arm, memory, disk_non_domestic, 
               disk_domestic, cache_disk, backplane, nic_non_domestic, nic_domestic, 
               sensor, riser_card, pcie_card_non_domestic, pcie_card_domestic, 
               motherboard, power_supply, raid_card_non_domestic, raid_card_domestic, 
               fiber, fan_non_domestic, fan_domestic, whole_machine, total_count, 
               created_at 
        FROM manufacturer_stats
    """)
    stats = cursor.fetchall()
    conn.close()
    
    return [dict(stat) for stat in stats]

def get_dashboard_data():
    """获取仪表盘数据"""
    # 获取总故障数
    conn = database.get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute("SELECT COUNT(*) as total FROM fault_details")
    total_faults = cursor.fetchone()[0]
    
    cursor.execute("SELECT COUNT(*) as unhandled FROM fault_details WHERE handling_result = '未处理'")
    unhandled_faults = cursor.fetchone()[0]
    
    # 获取最近的故障趋势数据
    cursor.execute("""
        SELECT phase, SUM(fault_handling_count) as total_count 
        FROM fault_counts 
        GROUP BY phase 
        ORDER BY created_at DESC 
        LIMIT 5
    """)
    trend_data = cursor.fetchall()
    
    conn.close()
    
    return {
        "total_faults": total_faults,
        "unhandled_faults": unhandled_faults,
        "trend_data": [dict(row) for row in trend_data]
    }